<!DOCTYPE html>
<html lang="zh">
  <head>
    <title>OSS直传</title>
    <style>
      /* 这里添加一些基础的样式，以便让用户界面看起来更好 */
      #uploadSuccessMessage {
        display: none;
      }
      /* 通用的模态框样式 */
      #notificationModal {
        position: fixed;
        top: 100px;
        left: 50%;
        transform: translate(-50%);
        padding: 10px;
        background-color: white;
        border: 1px solid #ddd;
        border-radius: 5px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
        z-index: 1000;
      }
    </style>
    <script>
      // 发送请求到 Cloudflare Worker 获取签名信息
      async function getOSSSignature() {
        const response = await fetch("https://oss.chengyishi.online/");
        const data = await response.json();
        return data;
      }

      // 执行文件上传
      async function uploadFile(file, signatureData) {
        const formData = new FormData();
        // 这里添加所有需要的字段，与后端 Worker 返回的保持一致
        const fileKey = "sass/k7/" + file.name; // 根据您 OSS 的命名规则自定义 key
        formData.append("key", fileKey);
        formData.append("OSSAccessKeyId", signatureData.accessKeyId);
        formData.append("policy", signatureData.policy);
        formData.append("Signature", signatureData.signature);
        formData.append("success_action_status", "200"); // OSS 成功上传后返回的 HTTP 状态码
        formData.append("file", file);

        try {
          const response = await fetch(signatureData.host, {
            method: "POST",
            body: formData,
          });

          if (response.ok) {
            console.log("上传成功！");
            showNotification("上传成功！");
            displaySuccessMessage(
              "https://oss.chengyishi.com" + "/" + fileKey
            );
          } else {
            console.log("上传失败！", response.status);
            showNotification("上传失败！");
            alert("上传失败：" + response.statusText);
          }
        } catch (error) {
          console.error("上传错误: ", error);
          alert("上传错误：" + error.message);
        }
      }

      function showNotification(message, duration = 3000) {
        const notificationModal = document.getElementById("notificationModal");
        const notificationMessage = document.getElementById(
          "notificationMessage"
        );

        // 设置通知信息并显示通知
        notificationMessage.textContent = message;
        notificationModal.style.display = "block";

        // 在指定的持续时间后隐藏通知
        setTimeout(() => {
          notificationModal.style.display = "none";
        }, duration);
      }

      // 显示成功消息和文件地址
      function displaySuccessMessage(url) {
        const successMessageElement = document.getElementById(
          "uploadSuccessMessage"
        );
        const fileUrlElement = document.getElementById("fileUrl");
        const copyUrlDiv = document.getElementById("copyUrlDiv");
        fileUrlElement.href = url;
        document.getElementById("url").textContent = url;
        fileUrlElement.setAttribute("data-url", url);

        fileUrlElement.addEventListener("click", function () {
          // 获取要复制的 URL
          const url = this.getAttribute("data-url");
          navigator.clipboard
            .writeText(url)
            .then(() => {
              // 显示通知消息
              showNotification("URL 已复制到剪贴板");
            })
            .catch((err) => {
              // 显示错误通知消息
              showNotification("无法复制 URL");
              console.error("无法复制 URL", err);
            });
        });
        // 显示上传成功的信息
        successMessageElement.style.display = "block";
      }

      window.onload = function () {
        const uploadForm = document.getElementById("uploadForm");
        uploadForm.onsubmit = async function (event) {
          event.preventDefault();
          const files = document.getElementById("fileInput").files;

          if (files.length > 0) {
            const signatureData = await getOSSSignature();
            await uploadFile(files[0], signatureData);
          }
        };
      };
    </script>
  </head>

  <body style="display: flex; justify-content: center; align-items: center; flex-direction: column; min-height: 500px;">
    <form id="uploadForm" style="margin-bottom: 20px">
      <input type="file" id="fileInput" />
      <input type="submit" value="上传文件" />
    </form>
    <div id="uploadSuccessMessage"></div>
    <div id="fileUrl">上传成功后点击这里复制 URL</div>
    <div id="url"></div>
    <div id="notificationModal" style="display: none">
      <p id="notificationMessage">通知信息</p >
    </div>
  </body>
</html>